package com.lill.org.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lill.common.component.transaction.CommonTransaction;
import com.lill.common.component.transaction.TM;
import com.lill.common.component.util.IdUtil;
import com.lill.common.component.util.Query;
import com.lill.org.dao.ICompanyArchitectureDao;
import com.lill.org.dao.IEmployeeDao;
import com.lill.org.dao.IPersonDao;
import com.lill.org.model.CompanyArchitectureModel;
import com.lill.org.model.EmployeeModel;
import com.lill.org.model.PersonModel;
import com.lill.org.service.IEmployeeService;
import com.lill.system.constant.SystemConstant;
import com.lill.system.model.SysUserEntity;
import com.lill.system.service.ISysUserRoleService;
import com.lill.system.service.ISysUserService;

/**
 * 员工管理Service实现类
 *
 * @author lill
 * @date 2019-04-25 20:45:24
 */
@Service("com.lill.org.service.impl.EmployeeServiceImpl")
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private IEmployeeDao employeeDao;
    @Autowired
    private IPersonDao personDao;
    @Autowired
    private ICompanyArchitectureDao architectureDao;
    @Lazy
    @Autowired
    private ISysUserService sysUserService;
    @Lazy
    @Autowired
    private ISysUserRoleService sysUserRoleService;


    public EmployeeModel queryObject(String id) {
    	EmployeeModel employee=employeeDao.queryObject(id);
    	if (employee != null ) {
			SysUserEntity userEntity=sysUserService.queryByPersonId(employee.getPersonId());
			if(null!=userEntity){
				List<String> roleIdList = sysUserRoleService.queryRoleIdList(userEntity.getId());
				if(null!=roleIdList&&!roleIdList.isEmpty()){
					employee.setRoleList(roleIdList);
				}
			}
		}
        return employee;
    }

    public List<EmployeeModel> queryList(Map<String, Object> map) {
        return employeeDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return employeeDao.queryTotal(map);
    }

//    @Transactional
    @CommonTransaction(value={TM.org,TM.sys})
    public int save(EmployeeModel employee) {
    	if(StringUtils.isEmpty(employee.getPersonId())){
    		String personId=IdUtil.createIdbyUUID();
    		PersonModel person=new PersonModel();
    		person.setId(personId);
    		person.setName(employee.getName());
    		person.setPhone(employee.getPhone());
    		person.setStatus(employee.getStatus());
    		person.setCreateTime(employee.getCreateTime());
    		person.setCreateUser(employee.getCreateUser());
    		personDao.save(person);
    		
    		SysUserEntity userEntity=new SysUserEntity();
    		userEntity.setUserName(employee.getPhone());
    		userEntity.setPersonId(personId);
    		userEntity.setStatus(employee.getStatus());
    		userEntity.setCreateTime(employee.getCreateTime());
    		userEntity.setCreateUser(employee.getCreateUser());
    		if(null==employee.getRoleList()||employee.getRoleList().isEmpty()){
    			userEntity.setRoleIdList(new ArrayList<String>());
    		}else{
    			userEntity.setRoleIdList(employee.getRoleList());
    			
    		}
    		sysUserService.save(userEntity);
    		employee.setPersonId(personId);
    	}else{
    		if(StringUtils.isNotEmpty(employee.getPhoneCode())){
    			Map<String, Object> mapParam=new HashMap<String, Object>();
    			mapParam.put("phone", employee.getPhone());
    			List<PersonModel> personList=personDao.queryList(mapParam);
    			if(null!=personList&&!personList.isEmpty()){
    				String[] personids = new String[personList.size()];
    				for (int i = 0; i < personList.size(); i++) {
    					personids[i]=personList.get(i).getId();
					}
    				//删除账号userid
    				mapParam=new HashMap<String, Object>();
        			mapParam.put("userName", employee.getPhone());
        			List<SysUserEntity> userList=sysUserService.queryList(mapParam);
        			
    				
        			//删除员工personId
    				List<String> employeeIdList=new ArrayList<String>();
    				List<EmployeeModel> employeeList=null;
    				for (int i = 0; i < personids.length; i++) {
    					mapParam=new HashMap<String, Object>();
    					mapParam.put("personId", personids[i]);
    					employeeList=employeeDao.queryList(mapParam);
						for (int j = 0; j < employeeList.size(); j++) {
							employeeIdList.add(employeeList.get(j).getId());
						}
					}
    				String[] employeeIds = new String[employeeIdList.size()];
    				employeeIds = employeeIdList.toArray(employeeIds);
    				
    				if(personids.length>0){
    					mapParam=new HashMap<String, Object>();
    					mapParam.put("ids", employeeIds);
    					employeeDao.deleteLogicByMap(mapParam);
    				}
    				
    				//删除人员
    				if(personids.length>0){
    					mapParam.put("ids", personids);
    					personDao.deleteLogicByMap(mapParam);
    				}
    				
    				String personId=IdUtil.createIdbyUUID();
    	    		PersonModel person=new PersonModel();
    	    		person.setId(personId);
    	    		person.setName(employee.getName());
    	    		person.setPhone(employee.getPhone());
    	    		person.setStatus(employee.getStatus());
    	    		person.setCreateTime(employee.getCreateTime());
    	    		person.setCreateUser(employee.getCreateUser());
    	    		personDao.save(person);
    	    		
    	    		if(null!=userList&&!userList.isEmpty()){
        				for (SysUserEntity sysUser : userList) {
        					sysUser.setPassWord(new Sha256Hash(SystemConstant.DEFAULT_OLD_PASS_WORD).toHex());
        					sysUser.setPersonId(personId);
        					sysUser.setStatus(employee.getStatus());
        					sysUser.setUpdateTime(employee.getCreateTime());
        					sysUser.setUpdateUser(employee.getCreateUser());
            	    		if(null==employee.getRoleList()||employee.getRoleList().isEmpty()){
            	    			sysUser.setRoleIdList(new ArrayList<String>());
            	    		}else{
            	    			sysUser.setRoleIdList(employee.getRoleList());
            	    		}
            	    		sysUserService.update(sysUser);
						}
        			}else{
        				SysUserEntity userEntity=new SysUserEntity();
        	    		userEntity.setUserName(employee.getPhone());
        	    		userEntity.setPersonId(personId);
        	    		userEntity.setStatus(employee.getStatus());
        	    		userEntity.setCreateTime(employee.getCreateTime());
        	    		userEntity.setCreateUser(employee.getCreateUser());
        	    		if(null==employee.getRoleList()||employee.getRoleList().isEmpty()){
        	    			userEntity.setRoleIdList(new ArrayList<String>());
        	    		}else{
        	    			userEntity.setRoleIdList(employee.getRoleList());
        	    		}
        	    		sysUserService.save(userEntity);
        			}
    	    		employee.setPersonId(personId);
    			}
    		}
    	}
    	employee.setId(IdUtil.createIdbyUUID());
    	
//    	architectureService.updateTreePersonNum(employee.getDepartId(), 1);
        return employeeDao.save(employee);
    }

    @CommonTransaction({TM.sys,TM.org})
    public int update(EmployeeModel employee) {
    	EmployeeModel employeeModel=employeeDao.queryObject(employee.getId());
    	List<SysUserEntity> userList=null;
    	
    	if(StringUtils.isNotEmpty(employee.getPhoneCode())){
    		Map<String, Object> mapParam=new HashMap<String, Object>();
			mapParam.put("phone", employee.getPhone());
			List<PersonModel> personList=personDao.queryList(mapParam);
			if(null!=personList&&!personList.isEmpty()){
				String[] personids = new String[personList.size()];
				for (int i = 0; i < personList.size(); i++) {
					personids[i]=personList.get(i).getId();
				}
				mapParam=new HashMap<String, Object>();
				mapParam.put("userName", employee.getPhone());
				userList=sysUserService.queryList(mapParam);
    			//删除员工
				List<String> employeeIdList=new ArrayList<String>();
				List<EmployeeModel> employeeList=null;
				for (int i = 0; i < personids.length; i++) {
					mapParam=new HashMap<String, Object>();
					mapParam.put("personId", personids[i]);
					employeeList=employeeDao.queryList(mapParam);
					for (int j = 0; j < employeeList.size(); j++) {
						employeeIdList.add(employeeList.get(j).getId());
					}
				}
				String[] employeeIds = new String[employeeIdList.size()];
				employeeIds = employeeIdList.toArray(employeeIds);
				
				if(personids.length>0){
					mapParam=new HashMap<String, Object>();
					mapParam.put("ids", employeeIds);
					employeeDao.deleteLogicByMap(mapParam);
				}
				//删除人员
				if(personids.length>0){
					mapParam.put("ids", personids);
					personDao.deleteLogicByMap(mapParam);
				}
			}
    	}
    	
    	PersonModel person=personDao.queryObject(employeeModel.getPersonId());
    	person.setName(employee.getName());
    	person.setPhone(employee.getPhone());
    	person.setUpdateTime(employee.getUpdateTime());
    	person.setUpdateUser(employee.getUpdateUser());
    	personDao.update(person);
    	
    	if(null!=userList&&!userList.isEmpty()){
    		SysUserEntity userEntity=sysUserService.queryByPersonId(person.getId());
    		for (SysUserEntity sysUser : userList) {
    			sysUser.setPersonId(person.getId());
    			sysUser.setPassWord(userEntity.getPassWord());
    			sysUser.setStatus(1);
    			sysUser.setUpdateTime(employee.getUpdateTime());
    			sysUser.setUpdateUser(employee.getUpdateUser());
    			if(null==employee.getRoleList()||employee.getRoleList().isEmpty()){
    				sysUser.setRoleIdList(new ArrayList<String>());
        		}else{
        			sysUser.setRoleIdList(employee.getRoleList());
        		}
    			sysUserService.update(sysUser,null);
			}
    	}else{
    		SysUserEntity userEntity=sysUserService.queryByPersonId(person.getId());
    		userEntity.setUserName(employee.getPhone());
    		userEntity.setUpdateTime(employee.getUpdateTime());
    		userEntity.setUpdateUser(employee.getUpdateUser());
    		if(null==employee.getRoleList()||employee.getRoleList().isEmpty()){
    			userEntity.setRoleIdList(new ArrayList<String>());
    		}else{
    			userEntity.setRoleIdList(employee.getRoleList());
    		}
    		sysUserService.update(userEntity,null);
    	}
    	
    	if(!employee.getDepartId().equals(employeeModel.getDepartId())){
    		CompanyArchitectureModel architecture=architectureDao.queryObject(employee.getDepartId());
    		Map<String, Object> mapParam=new HashMap<String, Object>();
    		mapParam.put("ids", (architecture.getParentList()+","+architecture.getId()).split(","));
    		mapParam.put("num", 1);
    		architectureDao.updatePersonNum(mapParam);
    		
    		CompanyArchitectureModel architectureOld=architectureDao.queryObject(employeeModel.getDepartId());
    		mapParam.put("ids", (architectureOld.getParentList()+","+architectureOld.getId()).split(","));
    		mapParam.put("num", -1);
    		architectureDao.updatePersonNum(mapParam);
    	}
        return employeeDao.update(employee);
    }

    public int delete(String id) {
        return employeeDao.delete(id);
    }

    public int deleteBatch(String[] ids) {
        return employeeDao.deleteBatch(ids);
    }
    
    @Transactional
	public int deleteLogicByMap(Map<String, Object> map) {
		String departId="";
		if(null!=map.get("ids")){
			String[] ids=(String[]) map.get("ids");
			if(ids.length>0){
				EmployeeModel employee=employeeDao.queryObject(ids[0]);
				if(null!=employee)
					departId=employee.getDepartId();
			}
		}
		int result=employeeDao.deleteLogicByMap(map);
		if(StringUtils.isNotEmpty(departId)){
			CompanyArchitectureModel architecture=architectureDao.queryObject(departId);
			Map<String, Object> mapParam=new HashMap<String, Object>();
			mapParam.put("ids", (architecture.getParentList()+","+architecture.getId()).split(","));
			mapParam.put("num", -1*result);
			architectureDao.updatePersonNum(mapParam);
		}
		return result;
	}

	public int updatePassword(Map<String, Object> mapParam) {
		return employeeDao.updatePassword(mapParam);
	}

	@Override
	public List<Map<String, Object>> queryPersonList(Map<String, Object> params) {
		return employeeDao.queryPersonList(params);
	}

	@Override
	public List<EmployeeModel> queryEmployeeList(Query query) {
		return  employeeDao.queryList(query);
	}

	@Override
	public EmployeeModel saveBackModel(EmployeeModel employee) {
		if(StringUtils.isEmpty(employee.getPersonId())){
    		String personId=IdUtil.createIdbyUUID();
    		PersonModel person=new PersonModel();
    		person.setId(personId);
    		person.setName(employee.getName());
    		person.setPhone(employee.getPhone());
    		person.setStatus(employee.getStatus());
    		person.setCreateTime(employee.getCreateTime());
    		person.setCreateUser(employee.getCreateUser());
    		personDao.save(person);
    		
    		SysUserEntity userEntity=new SysUserEntity();
    		userEntity.setUserName(employee.getPhone());
    		userEntity.setPersonId(personId);
    		userEntity.setStatus(employee.getStatus());
    		userEntity.setCreateTime(employee.getCreateTime());
    		userEntity.setCreateUser(employee.getCreateUser());
    		if(null==employee.getRoleList()||employee.getRoleList().isEmpty()){
    			userEntity.setRoleIdList(new ArrayList<String>());
    		}else{
    			userEntity.setRoleIdList(employee.getRoleList());
    			
    		}
    		sysUserService.save(userEntity);
    		employee.setPersonId(personId);
    	}
    	
    	employee.setId(IdUtil.createIdbyUUID());
    	
    	CompanyArchitectureModel architecture=architectureDao.queryObject(employee.getDepartId());
    	Map<String, Object> mapParam=new HashMap<String, Object>();
    	mapParam.put("ids", (architecture.getParentList()+","+architecture.getId()).split(","));
    	mapParam.put("num", 1);
    	architectureDao.updatePersonNum(mapParam);
    	
        employeeDao.save(employee);
		return employee;
	}

	@Override
	public String queryUserIdByEmployeeId(String employeeId) {
		return employeeDao.queryUserIdByEmployeeId(employeeId);
	}

	@Override
	public List<Map<String, Object>> queryPersonOhterList(Map<String, Object> params) {
		return employeeDao.queryPersonOhterList(params);
	}

	@Override
	public List<String> queryShopManagerUserIdByBranchId(String branchId) {
		return employeeDao.queryShopManagerUserIdByBranchId(branchId);
	}

	@Override
	public List<EmployeeModel> queryShopManagerEmployeeByBranchId(Map<String, Object> mapParam) {
		return employeeDao.queryShopManagerEmployeeByBranchId(mapParam);
	}

	@Override
	public List<Map<String, Object>> queryEmployeeByBranchId(Map<String, Object> params) {
		return employeeDao.queryEmployeeByBranchId(params);
	}

	@Override
	public List<Map<String, Object>> queryRepeatEmployee(String cid,String bid,String phones) {
		return employeeDao.queryRepeatEmployee(cid,bid,phones);
	}

	@Override
	public List<Map<String, Object>> queryCustomerBySendMsg(Map<String, Object> params) {
		return employeeDao.queryCustomerBySendMsg(params);
	}

	@Override
	public List<Map<String, Object>> queryEmpByMaintenance() {
		return employeeDao.queryEmpByMaintenance();
	}


}
